package com.burgeon.backend.SHOP.service.Impl;
/**
 * 团购订单
 */

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.mappers.GoodsMapper;
import com.burgeon.backend.SHOP.mappers.GroupMapper;
import com.burgeon.backend.SHOP.mappers.GroupOrderMapper;
import com.burgeon.backend.SHOP.service.GroupOrderService;
import com.burgeon.backend.SHOP.service.OrderService;
import com.burgeon.backend.SHOP.service.ShopMessageTemplateService;
import com.burgeon.backend.SHOP.service.ex.OrderExceptionApp;
import com.burgeon.backend.service.QueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GroupOrderServiceImpl implements GroupOrderService {
    @Autowired
    private GroupOrderMapper groupOrderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private ShopMessageTemplateService shopMessageTemplateService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private QueueService queueService;

    @Override
    public HashMap orderResult(String gid, String oid, String uid, String token) {
        HashMap data = new HashMap();

        Group group = groupMapper.getGroupById(gid);

        Goods goods = groupMapper.showGoodsById(group.getGid());
        group.setGoods(goods);
        data.put("goods", group);

        ArrayList Recommend = new ArrayList();
        List<Group> groupList = groupMapper.showRecommendGroup(token);//查询拼团商品
        for (Group groupData : groupList) {
            Goods goodsData = groupMapper.showGoodsById(groupData.getGid());
            groupData.setSum(groupMapper.showGroupSumByGrid(groupData.getId()));
            groupData.setGoods(goodsData);
            Recommend.add(groupData);
        }
        data.put("recommend", Recommend);

        OrderResult orderResult = orderService.GetLatestOrder(oid, uid, token);
        data.put("orderResult", orderResult);
        //失败
        //根据oid找到团购单明细 找到所属团购单
        //团购单人数减1
        //人数为0删除
        //删除item
        GroupItem groupItem = groupOrderMapper.getgetGroupItemByOid(oid);
        GroupOrder groupOrder = groupMapper.getGroupOrder(groupItem.getGroupId());
        if ("ERROR".equals(orderResult.getState())){
            if (groupOrder.getNowNumber()<2){
                groupOrderMapper.delGroupOrder(groupOrder.getId());
            }else {
                groupOrderMapper.upGroupNumber(groupOrder.getId(), groupOrder.getNowNumber() - 1);
            }

            groupOrderMapper.delGroupOrderItem(groupItem.getId());
        }

        List<GroupItem> groupItems = groupMapper.getGroupItem(groupItem.getGroupId());

        data.put("groupItem", groupItems);

        data.put("date", groupOrder.getEndTime());

        data.put("lack", groupOrder.getNumber() - groupOrder.getNowNumber());

        return data;
    }

    //加入团购支付
    @Override
    @Transactional
    public PayData addGroupOrder(String grid, String groupOrderId, String mid, String uid,
                                 String aid, String cid, String code, String phone, String type,
                                 String openid, String token,String comment,String emp) throws OrderExceptionApp {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());

        Group group = groupOrderMapper.findGroupById(grid);
        PayData data = orderService.groupCreateOrder(uid, openid, aid, group.getPrice(), mid, group.getGid(), cid, code, type, phone, token,comment,emp);

        GroupOrder groupOrder = joinGroup(groupOrderId,token);

        createGroupItem(groupOrderId, data.getOrderId(), "N", uid, token);

        //判断是否埋怨
        if (groupOrder.getNowNumber()+1 == groupOrder.getNumber()) {
            //人数已满 修改状态已完成
            //发送模板消息
            Goods goods = goodsMapper.getGoods(group.getGid());
            ArrayList<GroupItem> groupItems = groupMapper.FindOrderIdmByGid(groupOrder.getId());
            for (GroupItem groupItem2:groupItems) {
                GroupItem groupItem = groupMapper.getGroupItemByUidAndOrderId(groupItem2.getOrderId());
//                System.err.println(groupItem);
                queueService.putGroup(groupItem.getOpenid(),groupItem.getOrderId(),token,now,goods.getName());
//                shopMessageTemplateService.sendGroup(groupItem.getOpenid(),groupItem.getOrderId(),token,now,goods.getName());
            }


        }

        return data;
    }

    //创建团购支付
    @Override
    @Transactional
    public PayData createGroup(String grid, String mid, String uid, String aid, String cid, String code,
                               String phone, String type, String openid, String token,String comment,String emp) throws OrderExceptionApp {
        Group group = groupOrderMapper.findGroupById(grid);

        PayData data = orderService.groupCreateOrder(uid, openid, aid, group.getPrice(), mid, group.getGid(), cid, code, type, phone, token,comment,emp);
        GroupOrder groupOrder = newGroupOrder(group, uid, token);
        createGroupItem(groupOrder.getId(), data.getOrderId(), "Y", uid, token);

        return data;
    }

    //创建团购单
    private GroupOrder newGroupOrder(Group group, String uid, String token) throws OrderExceptionApp {

        //创建时间
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(group.getDate()));
        Date da = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //创建拼团开始时间
        String startTime = sdf.format(date);
        String endTime = sdf.format(da);
        //拼团结束时间

        //创建拼团订单对象
        GroupOrder groupOrder = new GroupOrder();
        groupOrder.setStartTime(startTime);
        groupOrder.setEndTime(endTime);
        groupOrder.setGrid(group.getId());
        groupOrder.setNumber(Integer.parseInt(group.getNumber()));
        groupOrder.setNowNumber(1);
        groupOrder.setInitiatorId(uid);

        groupOrder.setState("1");
        groupOrder.setToken(token);
        Integer row = groupOrderMapper.insertGroupOrder(groupOrder);
        if (1 != row) {
            throw new OrderExceptionApp("出现错误");
        }
        return groupOrder;
    }

    /**
     * 加入团购
     */
    public GroupOrder joinGroup(String grid,String token) throws OrderExceptionApp {
         //判断团购人数 人数满足报错
        GroupOrder groupOrder = groupMapper.getGroupOrder(grid);
        if (groupOrder.getNowNumber() >= groupOrder.getNumber()) {
            throw new OrderExceptionApp("人数已满");
        }

        //增加现有人数
        groupOrderMapper.upGroupNumber(grid, groupOrder.getNowNumber() + 1);

        //判断人数 是否拼团完成

        if (groupOrder.getNowNumber()+1 == groupOrder.getNumber()) {
            //人数已满 修改状态已完成
            groupOrderMapper.upGroupState(grid,"2");

        }
        return groupOrder;
    }

    /**
     * 创建团购单明细
     */
    public void createGroupItem(String gid, String oid, String isCreator, String uid, String token) {

        //创建item
        GroupItem groupItem = new GroupItem();
        groupItem.setGroupId(gid);
        groupItem.setIsCreator(isCreator);
        groupItem.setOrderId(oid);
        groupItem.setUid(uid);
        groupItem.setToken(token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());
        groupItem.setDate(now);

        groupOrderMapper.createGroupItem(groupItem);
    }


}
